###############################################################################
# Mailer.pl                                                                   #
###############################################################################
# YaBB: Yet another Bulletin Board                                            #
# Open-Source Community Software for Webmasters                               #
# Version:        YaBB 2.2                                                    #
# Packaged:       November 8, 2007                                            #
# Distributed by: http://www.yabbforum.com                                    #
# =========================================================================== #
# Copyright (c) 2000-2007 YaBB (www.yabbforum.com) - All Rights Reserved.     #
# Software by:  The YaBB Development Team                                     #
#               with assistance from the YaBB community.                      #
# Sponsored by: Xnull Internet Media, Inc. - http://www.ximinc.com            #
#               Your source for web hosting, web design, and domains.         #
###############################################################################

$mailerplver = 'YaBB 2.2 $Revision: 1.25 $';
if ($action eq 'detailedversion') { return 1; }

sub sendmail {
	my ($to, $subject, $message, $from, $mailcharset) = @_;

	# Do a FromHTML here for $to, and for $mbname
	# Just in case has special chars like & in addresses
	&FromHTML($to);
	&FromHTML($mbname);

	# Change commas to HTML entity - ToHTML doesn't catch this
	# It's only a problem when sending emails, so no change to ToHTML.
	$mbname =~ s/,/&#44;/ig;

	$charsetheader = $mailcharset ? $mailcharset : $yycharset;
	$fromheader = $from ? "$from" : "$mbname <$webmaster_email>";
	$toheader   = $to   ? "$to"   : "$mbname $smtp_txt{'555'} <$webmaster_email>";
	unless ($from) { $from = $webmaster_email; }
	$to              =~ s/[ \t]+/, /g;
	$webmaster_email =~ s/.*<([^\s]*?)>/$1/;
	$message         =~ s/^\./\.\./gm;
	#$message         =~ s/\r\n/\n/g;
	#$message         =~ s/\n/\r\n/g;
	$message 	     =~ s/[\r\n]/\n/g; 
	$message         =~ s/<\/*b>//g;
	$smtp_server     =~ s/^\s+//g;
	$smtp_server     =~ s/\s+$//g;
	if (!$to) { return; }

	# Thanks to Graham J for your contribution to this routine
	if ($mailtype == 1) {
		$smtp_to = $to;
		$smtp_from = $from;
		$smtp_message = $message;
		$smtp_subject = $subject;
		$smtp_charset = $charsetheader;
		require "$sourcedir/Smtp.pl";
		&use_smtp;
	}
	if ($mailtype == 2) {
		eval q^
			use Net::SMTP;
			my $smtp = Net::SMTP->new(
				Host => $smtp_server, 
				Hello => $smtp_server, 
				Timeout => 30,
				Debug => 0,
			) || die "unable to create Net::SMTP object $smtp_server.";
			$smtp->mail($from); 
			foreach (split(/, /, $to)) {
				$smtp->to($_);
			}
			$smtp->data(); 
			$smtp->datasend("To: $toheader\r\n"); 
			$smtp->datasend("From: $fromheader\r\n"); 
			$smtp->datasend("X-Mailer: YaBB Net::SMTP\r\n"); 
			$smtp->datasend("Subject: $subject\r\n");
			$smtp->datasend("Content-Type: text/plain\; charset=$charsetheader\r\n");
			$smtp->datasend("\r\n");
			$smtp->datasend($message);
			$smtp->dataend();
			$smtp->quit();
		^;
		if ($@) {
			&fatal_error("net_fatal","$error_txt{'error_verbose'}: $@");
			return -77;
		}
		return 1;
	}
	if ($mailtype == 0) {
		open(MAIL, "|$mailprog -t");
		print MAIL "To: $toheader\n";
		print MAIL "From: $fromheader\n";
		print MAIL "X-Mailer: YaBB Sendmail\n";
		print MAIL "Subject: $subject\n";
		print MAIL "Content-Type: text/plain\; charset=$charsetheader\n\n";
		$message =~ s/\r\n/\n/g;
		print MAIL "$message\n";
		close(MAIL);
		return (1);
	}
	if($mailtype == 3) {
		# Dummy mail engine
		fopen(MAIL, ">>$vardir/mail.log");
		print MAIL "Mail sent at " . scalar localtime() . "\n";
		print MAIL "To: $toheader\n";
		print MAIL "From: $fromheader\n";
		print MAIL "X-Mailer: YaBB Sendmail\n";
		print MAIL "Subject: $subject\n\n";
		$message =~ s/\r\n/\n/g;
		print MAIL "$message\n";
		print MAIL "End of Message\n\n";
		fclose(MAIL);
	}
}

sub CallTo {
	if ($iamguest) { &fatal_error("members_only"); }
	my $callusername = $INFO{'username'};
	&LoadUser($callusername);    # If user is not in memory, s/he must be loaded.
	if (!${$uid.$callusername}{'skype'}){
		return;	
	}
	print "Content-Type: text/html\n\n";
	$refresh = qq~<html>\n<head>\n
	<script>
		var tik=0
		function timer() {
		  	window.setTimeout("timer()", 2000)
			tik=tik+1
			if(tik==2){
				window.close()
			}
		}
	</script>
	</head>\n
	<body Onload = document.location="callto://${$uid.$callusername}{'skype'}">\n
	<font face="Arial" size="2">$dereftxt{'3'}</font>\n
	<script language="JavaScript1.2" type="text/javascript">\n
	timer();
	</script>
	</body></html>\n~;
	print $refresh;
}

sub MailTo {
	require "$sourcedir/Decoder.pl";
	if ($iamguest) { &fatal_error("members_only"); }
	my $mailusername = $INFO{'username'};
	my $mailcrypted  = $INFO{'mail_id'};
	&LoadUser($mailusername);    # If user is not in memory, s/he must be loaded.
	if (${$uid.$mailusername}{'email'} && (${$uid.$mailusername}{'hidemail'} ne "checked" || $iamadmin) && $mailusername ne "Guest") {
		$truemail = ${$uid.$mailusername}{'email'};
	} elsif ($mailusername eq "Guest") {
		$truemail = &descramble($mailcrypted, $mailusername);
	} else {
		fatal_error("email_no_access");
	}
	print "Content-Type: text/html\n\n";
	$refresh = qq~<html>\n<head>\n
	<script>
		var tik=0
		function timer() {
		  	window.setTimeout("timer()", 2000)
			tik=tik+1
			if(tik==2){
				window.close()
			}
		}
	</script>
	</head>\n
	<body Onload = document.location="mailto:$truemail">\n
	<font face="Arial" size="2">$dereftxt{'3'}</font>\n
	<script language="JavaScript1.2" type="text/javascript">\n
	timer();
	</script>
	</body></html>\n~;
	print $refresh;
}

# Before &sendmail is called, the message MUST be run through here.
# First argument is the message
# Second argument is a hashref to the replacements
# Example:
#  $message = qq~Hello, {yabb username}! The answer is {yabb answer}!~;
#  $message = &template_email($message, {username => $username, answer => 42});
# Result (with $username being the actual username):
#  Hello, $username! The answer is 42!
sub template_email {
	my($message, $info);
	$message = $_[0];
	$info = $_[1];
	foreach my $key (keys(%$info)) {
		$message =~ s/\Q{yabb $key}\E/$info->{$key}/g;
		$message =~ s/\Q<yabb $key>\E/$info->{$key}/g;
	}
	$message =~ s/\Q{yabb scripturl}\E/$scripturl/g;
	$message =~ s/\Q<yabb scripturl>\E/$scripturl/g;
	$message =~ s/\Q{yabb mbname}\E/$mbname/g;
	$message =~ s/\Q<yabb mbname>\E/$mbname/g;
	return $message;
}

## send pm alert instead of email one
sub sendPMalert	{
	my ($to, $subject, $message, $from) = @_;
	my $messageid = &getnewid;
	fopen(INBOX, "$memberdir/$to.msg");
	@inmessages = <INBOX>;
	fclose(INBOX);
	fopen(INBOX, ">$memberdir/$to.msg");
	# new format:  #messageid|from user|touser(s)|(ccuser(s))|(bccuser(s))|
	#    subject|date|message|(parentmid)|(reply#)|ip|
	#		messagestatus|flags|storefolder|attachment
	print INBOX "$messageid|$from|$to|||$subject|$date|$message|$messageid|0|$ENV{'REMOTE_ADDR'}|n|u||\n";
	print INBOX @inmessages;
	fclose(INBOX);
	;
		
}


1;